package com.meitianhui.convenitenbuy.util;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Type;

public class GsonParserUtils {
	private static GsonParserUtils gsonParser;

	private static Gson gson;

	private GsonParserUtils() {

	}

	public static GsonParserUtils getInstance() {
		if (gsonParser == null) {
			gsonParser = new GsonParserUtils();
			gson = new Gson();
		}

		return gsonParser;
	}

	public <T> T getBean(String jsonString, Class<T> cls) throws Exception {
		T t = null;
		try {
			t = gson.fromJson(jsonString, cls);
		} catch (Exception e) {
			Log.d("errorInfo", "-->" + e.toString());
			throw  new Exception("数据解析异常", e);
		}
		return t;
	}

	public <T> T fromJson(String json, TypeToken<T> token) throws Exception {

		if (json==null||"".equals(json)) {
			return null;
		}

		try {
			return gson.fromJson(json, token.getType());
		} catch (Exception e) {
			throw  new Exception("数据解析异常", e);
		}

	}

	public String toJson(Object obj) {
		return gson.toJson(obj);
	}

	/**
	 * 解析本地的地区选择的json
	 *
	 * @param context
	 * @param resId
	 * @param
	 */
	public Object parserRegionJson(final Context context, final int resId, final Type responseType) {
		Object o = null;
		try {
			InputStream inStream = context.getResources().openRawResource(resId);
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = inStream.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			byte[] in2b = swapStream.toByteArray();
			String json = new String(in2b);
			Gson gson = new Gson();

			o = gson.fromJson(json, responseType);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return o;
	}
}
